﻿using System;
using System.Configuration;
using System.Linq;
using Models;
using NetDimension.Weibo;

namespace BLL
{
    public class SinaService:BaseService
    {
        private UserService _userService;
        private WebWorkContext _context;
        private AuthenticationService _authenticationService;

        public SinaService()
        {
            _userService = new UserService();
            _context =new WebWorkContext();
            _authenticationService = new AuthenticationService();
        }

       

        public OAuth GetLoginOAuth()
        {
            var appKey = ConfigurationManager.AppSettings["appKey"];
            var appSecret = ConfigurationManager.AppSettings["appSecret"];

            var callbackUrl = ConfigurationManager.AppSettings["SinaLoginReturnUrl"];

            var oauth = new OAuth(appKey, appSecret, callbackUrl);
            return oauth;
        }

        public OAuth GetSmallLoginOAuth()
        {
            var appKey = ConfigurationManager.AppSettings["smallAppKey"];
            var appSecret = ConfigurationManager.AppSettings["smallAppSecret"];

            var callbackUrl = ConfigurationManager.AppSettings["SinaSmallLoginReturnUrl"];

            var oauth = new OAuth(appKey, appSecret, callbackUrl);
            return oauth;
        }



        public OAuth GetBindAuth()
        {
            var appKey = ConfigurationManager.AppSettings["bindAppKey"];
            var appSecret = ConfigurationManager.AppSettings["bindAppSecret"];

            var callbackUrl = ConfigurationManager.AppSettings["SinaBindReturnUrl"];

            var oauth = new OAuth(appKey, appSecret, callbackUrl);
            return oauth;

        }



        public WeiboUser GetSinaWeiboUserInfo(string code, OAuth oauth)
        {
            try
            {

                var accessToken = oauth.GetAccessTokenByAuthorizationCode(code);
                var token = accessToken.Token;
                var client = new Client(oauth);

                var entity = client.API.Users.Show(uid: client.API.Account.GetUID());
                var userInfo = new WeiboUser()
                                   {
                                       id = entity.ID,
                                       name = entity.Name,
                                       Token = token,
                                       profile_image_url = entity.ProfileImageUrl,
                                       Code = code
                                   };
               
                return userInfo;
            }
            catch (WeiboException weiboException)
            {

                //ApplicationLog.Error("调用微博接口发生异常:", weiboException);
            }
            return null;
        }

        public bool IsNewSinaWeiboUser(string weiboId)
        {
            var query = from connect in db.User_WeiboLogin_Bounds
                        where connect.WeiboUserId == weiboId
                        select connect;
            return !query.Any();
        }

        public bool IsCurrentUserBindToWeibo(int userId)
        {
            var query = from connect in db.User_WeiboLogin_Bounds
                        where connect.UserId == userId
                        select connect;
            return query.Any();
        }

        

      

        public void CreateWeiboUserAndBind(WeiboUser weiboUserInfo, string name, string email)
        {
            if (_context.CurrentUser.IsRegistered())
            {

                //Already registered customer. 
                _authenticationService.SignOut();
                
                //Save a new record
                _userService.InsertGuestCustomer();
            }

            var user = _context.CurrentUser;

            _userService.ActiveUser(user.Id, name, email); 

            _userService.BindSinaUser(user.Id, weiboUserInfo.id);
        }

        public void UpdateWeiboUserToken(string id, string token)
        {
            var query = from w in db.User_At_SinaWeibos
                        where w.WeiboUserId == id
                        select w;

            var u = query.FirstOrDefault();
            if(u!=null)
            {
                u.Token = token;
                db.SubmitChanges();
            }
        }

        public void CreateWeiboUser(WeiboUser weiboUserInfo)
        {
            var query = from w in db.User_At_SinaWeibos
                        where w.WeiboUserId == weiboUserInfo.id
                        select w;

            if(!query.Any())
            {
                var u = new User_At_SinaWeibo();
                u.Name = weiboUserInfo.name;
                u.WeiboUserId = weiboUserInfo.id;
                u.Token = weiboUserInfo.Token;
                u.LastRefreshTime = DateTime.Now;
                u.ExpireIn = (int)weiboUserInfo.expires_in;
                u.Secret = string.Empty;
                u.AddTime = DateTime.Now;

                db.User_At_SinaWeibos.InsertOnSubmit(u);
                db.SubmitChanges();
            }
        }


        public bool IsWeiboBind2OtherUser(string weiboUserId, int userId)
        {
            var query = from connect in db.User_WeiboLogin_Bounds
                        where connect.WeiboUserId == weiboUserId && connect.UserId != userId
                        select connect;
            return query.Any();
        }

        public void BindWeiboUser(string weiboId, int userId)
        {
            _userService.BindSinaUser(userId, weiboId);
        }

        public void PostToWeibo(int userId, string content)
        {
            try
            {


                var query = from connect in this.db.User_WeiboLogin_Bounds
                            where connect.UserId == userId
                            select connect;
                if (query.Any())
                {
                    var weiboUserId = query.First()
                        .WeiboUserId;
                    var weiboQuery = from weibo in this.db.User_At_SinaWeibos
                                     where weibo.WeiboUserId == weiboUserId
                                     select weibo;


                    var weiboUser = weiboQuery.First();
                    var token = weiboUser.Token;

                    var oauth = this.GetOAuth(token);

                    var client = new Client(oauth);

                    client.API.Statuses.Update(content);
                }
                else
                {
                    throw new Exception("没有绑定微博");
                }
            }catch(Exception e)
            {
                
            }
        }

        private OAuth GetOAuth(string token)
        {
            var appKey = ConfigurationManager.AppSettings["appKey"];
            var appSecret = ConfigurationManager.AppSettings["appSecret"];


            var oauth = new OAuth(appKey, appSecret, token, null);
            return oauth;
        }

    }
}